package parser

import (
	"regexp"
	"spider/engine"
	"spider/model"
	"strconv"
)

var OccuPationRe = regexp.MustCompile(
	`<td><span class="label">职业：[^>]*>([^<]+)</td>`)

var AgeRe = regexp.MustCompile(
	`<td><span class="label">年龄：[^>]*>([^岁]+)岁</td>`)

var HeightRe = regexp.MustCompile(
	`<td><span class="label">身高：</span>([0-9]+)CM</td>`)

var WeightRe = regexp.MustCompile(
	`<td><span class="label">体重：[^>]*>([^<]+)</span></td>`)

var GenderRe = regexp.MustCompile(
	`<td><span class="label">性别：</span><span field="">([^<]+)</span></td>`)

var InComeRe = regexp.MustCompile(
	`<td><span class="label">月收入：</span>([^<]+)</td>`)

var Marriage = regexp.MustCompile(
	`<td><span class="label">婚况：</span>([^<]+)</td>`)

var EducationRe = regexp.MustCompile(
	`<td><span class="label">学历：</span>([^<]+)</td>`)

var HoKouRe = regexp.MustCompile(
	`  <td><span class="label">籍贯：</span>([^<]+)</td>`)

var XingZuoRe = regexp.MustCompile(
	`<td><span class="label">星座：</span><span field="">([^<]+)</span></td>`)

var HouseRe = regexp.MustCompile(
	` <td><span class="label">住房条件：</span><span field="">([^<]+)</span></td>`)

var CarRe = regexp.MustCompile(
	`<td><span class="label">是否购车：</span><span field="">([^<]+)</span></td>`)

var IdRe = regexp.MustCompile(
	`"http://album.zhenai.com/u/([0-9]+)"`)

func ParserProfile(contents []byte, url, name string) engine.ParseResult {
	profile := model.Profile{}

	profile.Name = name
	Age, err := strconv.Atoi(extractString(contents, AgeRe))
	if err == nil {
		profile.Age = Age
	}

	Height, err := strconv.Atoi(extractString(contents, HeightRe))
	if err == nil {
		profile.Height = Height
	}

	Weight, err := strconv.Atoi(extractString(contents, WeightRe))
	if err == nil {
		profile.Weight = Weight
	}

	profile.Gender = extractString(contents, GenderRe)
	profile.HoKou = extractString(contents, HoKouRe)
	profile.House = extractString(contents, HouseRe)
	profile.Income = extractString(contents, InComeRe)
	profile.Marriage = extractString(contents, Marriage)
	profile.Occupation = extractString(contents, OccuPationRe)
	profile.Education = extractString(contents, EducationRe)
	profile.Xingzuo = extractString(contents, XingZuoRe)
	profile.Car = extractString(contents, CarRe)
	result := engine.ParseResult{
		Items: []engine.Item{
			{
				Url:     url,
				Id:      extractString(contents, IdRe),
				Type:    "zhanai",
				Payload: profile,
			},
		},
	}
	return result
}

func extractString(contents []byte, re *regexp.Regexp) string {
	matchs := re.FindSubmatch(contents)
	if len(matchs) >= 2 {
		return string(matchs[1])
	}
	return ""
}
